package com.example.sharding.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;

/**
 * Created by liunanhua on 2018/3/19.
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Value("${spring.servlet.multipart.max-file-size:1}")
    private int maxFileSize;
    @Value("${spring.servlet.multipart.max-request-size:1024}")
    private int maxRequestSize;


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/static")
                .addResourceLocations("classpath:/META-INF/resources/static/");
        registry.addResourceHandler("/webjars*")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 通过cors协议解决跨域问题
     * 更细致也可以使用@CrossOrigin这个注解在controller类中使用。
     * @CrossOrigin(origins = "http://localhost:8081", maxAge = 3600)
     * @return
     */
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("*")
                        .allowCredentials(true)
                        .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
                        .maxAge(3600);
            }
        };
    }

    /**
     * 配置文件上传
     */
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个数据大小,文件最大10M,DataUnit提供5中类型B,KB,MB,GB,TB
        factory.setMaxFileSize(DataSize.of(maxFileSize, DataUnit.MEGABYTES));
        // 总上传数据大小,设置总上传数据总大小100G
        factory.setMaxRequestSize(DataSize.of(maxRequestSize, DataUnit.MEGABYTES));
        return factory.createMultipartConfig();
    }


}
